package db_main

import (
	"errors"
	"fmt"
	"gorm.io/gorm"
	"longmen/server/config/global"
	"longmen/server/pkg/common/helper/util"
	"longmen/server/pkg/db/mysql"
	"longmen/server/pkg/db/mysql/models/models_main"
)

func GetUserOnlinetimeParam(param map[string]interface{}) (*models_main.UserOnlinetime, error) {
	fName := "GetUserOnlinetimeParam"
	o := &models_main.UserOnlinetime{}
	table := mysql.GetRTable(&models_main.UserOnlinetime{})
	mysql.Condition(table, param, "", "", 0, 0)
	err := table.Find(o).Error
	if errors.Is(err, gorm.ErrRecordNotFound) {
		err = nil
	}
	if err != nil {
		err = fmt.Errorf("%s%s", util.Convert(fName), err.Error())
	}
	return o, err
}

func InsertUserOnlinetime(session *gorm.DB, online *models_main.UserOnlinetime) error {
	fName := "InsertUserOnlinetime"
	if session == nil {
		session = global.GetX()
	}
	err := session.Create(online).Error
	if err != nil {
		session.Rollback()
		return fmt.Errorf("%s%s", util.Convert(fName), err.Error())
	}
	return nil
}

func UpdateUserOnlinetime(session *gorm.DB, columns []string, online *models_main.UserOnlinetime) error {
	fName := "UpdateUserOnlinetime"
	if session == nil {
		session = global.GetX()
	}
	err := session.Where("uid = ?", online.Uid).Select(columns).Updates(online).Error
	if err != nil {
		session.Rollback()
		return fmt.Errorf("%s%s", util.Convert(fName), err.Error())
	}
	return nil
}
